import React, { Fragment } from 'react'
import {
  Typography,
  Layout,
  Tree,
  Alert,
  Icon,
  Button,
  Tooltip,
  List,
  Card,
  Tag,
  Table,
  Modal,
  InputNumber,
  Input,
  Select,
  Tabs,
  message,
  Switch,
} from 'antd'
import { withI18n, Trans } from '@lingui/react'
import { connect } from 'dva'
import { Page } from 'components'
import { stringify } from 'qs'
// import Filter from './component/Filter'
// import { router } from 'utils'
// import { UserLink, ProjectLink, DeviceLink } from 'components'
// import moment from 'moment'
const { Paragraph, Title } = Typography
const { Sider, Content } = Layout
const { TreeNode } = Tree
const { TabPane } = Tabs

Array.prototype.remove = function(val) {
  var index = this.indexOf(val)
  if (index > -1) {
    this.splice(index, 1)
  }
}

const LightStrategyKey = 'STRATEGY'
const LightKey = 'LIGHT'
const topHieght = 400
const cmdlistHeight = 240
const extraspropsheight = 160

@withI18n()
@connect(({ multicmd, app, loading }) => {
  const { isMobile } = app
  return { multicmd, isMobile, loading }
})
class ProjectDeviceList extends React.Component {
  state = {
    expandedKeys: [],
    selectedKeys: [],

    selectLength: 0,
  }

  componentDidMount() {}

  render() {
    //#region
    const { location, i18n, multicmd, isMobile, loading, dispatch } = this.props
    const { projects, deviceIds, checkedKeys } = multicmd
    console.log(checkedKeys)
    const onCheck = (checkedKeys, e) => {
      const { checked, checkedNodes, node, event } = e
      var notProjet = !node.props.dataRef.ProjectName
      // console.log(node)

      if (notProjet) {
        dispatch({ type: 'multicmd/updateState', payload: { checkedKeys } })
      } else {
        if (node.props.children == undefined) {
        } else {
          checkedKeys.remove(node.props.dataRef.objectId)
          dispatch({ type: 'multicmd/updateState', payload: { checkedKeys } })
        }
      }
    }
    const onSelect = (selectedKeys, info) => {
      this.setState({ selectedKeys })
    }
    const onExpand = expandedKeys => {
      // console.log('onExpand', expandedKeys)
      this.setState({
        expandedKeys,
      })
    }
    const onLoadData = treeNode => {
      return new Promise(resolve => {
        dispatch({
          type: 'multicmd/queryDevices',
          payload: { resolve, project: treeNode.props.dataRef.objectId },
        })
      })
    }
    //
    const renderTreeNodes = (projects.length > 3 ? projects.slice(3) : []).map(
      projectItem => {
        const { objectId, ProjectName } = projectItem
        const devices = deviceIds[objectId]
        return (
          <TreeNode
            title={
              <span style={{ fontWeight: 'bold' }}>
                <Icon type="folder" />
                &nbsp;{ProjectName}
              </span>
            }
            key={objectId}
            dataRef={projectItem}
            style={{ padding: 0, margin: 0 }}
            disableCheckbox={devices == undefined || devices.length <= 0}
          >
            {devices &&
              devices.map((deviceItem, index) => {
                const { DeviceName, objectId } = deviceItem
                return (
                  <TreeNode
                    isLeaf={true}
                    icon={<Icon type="file" />}
                    title={
                      <span>
                        <Icon type="bulb" />
                        &nbsp;{DeviceName}
                      </span>
                    }
                    key={objectId}
                    dataRef={deviceItem}
                  />
                )
              })}
          </TreeNode>
        )
      }
    )
    const selected = checkedKeys.length
    //#endregion
    return (
      <Sider
        width={250}
        style={{
          background: 'transparent',
          padding: 0,
          margin: 0,
        }}
      >
        <Alert
          message={
            <Fragment>
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  marginRight: 5,
                }}
              >
                <Title level={4} style={{}}>
                  <Trans>Device List</Trans>:
                </Title>
                <Alert
                  message={
                    <div
                      style={{
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                      }}
                    >
                      <div
                        style={{
                          fontWeight: 'bold',
                          marginRight: 5,
                        }}
                      >{i18n.t`${selected} items have been selected`}</div>
                      <div style={{ display: 'inline' }}>
                        <Tooltip title={i18n.t`Clear Selection`}>
                          <Button
                            size="small"
                            onClick={e => {
                              dispatch({
                                type: 'multicmd/updateState',
                                payload: { checkedKeys: [] },
                              })
                            }}
                          >
                            <Icon type="delete" />
                          </Button>
                        </Tooltip>
                      </div>
                    </div>
                  }
                  style={{
                    marginBottom: 5,
                    background: '#fff',
                  }}
                />
              </div>

              <div
                style={{
                  overflowX: 'scroll',
                  height: '100%',
                }}
              >
                <Tree
                  checkable
                  selectable={false}
                  onExpand={onExpand}
                  expandedKeys={this.state.expandedKeys}
                  autoExpandParent={false}
                  onCheck={onCheck}
                  checkedKeys={checkedKeys}
                  onSelect={onSelect}
                  loadData={onLoadData}
                  style={{
                    padding: 0,
                    margin: 0,
                    width: 200,
                    background: 'transparent',
                    minHeight: topHieght - 10,
                  }}
                >
                  {renderTreeNodes}
                </Tree>
              </div>
            </Fragment>
          }
          style={{
            background: 'transparent',
            borderColor: 'transparent',
            margin: 0,
            padding: 0,
          }}
        />
      </Sider>
    )
  }
}

@withI18n()
@connect(({ multicmd, app, loading }) => {
  const { isMobile } = app
  return { multicmd, isMobile, loading }
})
class EditStrategy extends React.Component {
  emptyState = {
    create_Name: undefined,
    create_Note: undefined,
    create_Datas: undefined,

    modify_objectId: undefined,
    modify_Name: '',
    modify_Note: '',
    modify_Datas: undefined,

    selectedStrategy: undefined,
  }
  state = { ...this.emptyState }

  // componentWillUnmount() {
  //   this.setState({ ...this.emptyState })
  // }

  render() {
    const { multicmd, i18n, dispatch, loading } = this.props
    const {
      nowKey,
      EditStrategyShow,
      EditingStrategy,
      AllStrategy,
      choosedCmds,
    } = multicmd
    const {
      create_Name,
      create_Note,
      create_Datas,

      modify_objectId,
      modify_Name,
      modify_Note,
      modify_Datas,
      selectedStrategy,
    } = this.state
    const defaultValue = [
      { '0': 0, '1': 0, '2': 0 },
      { '0': 0, '1': 0, '2': 0 },
      { '0': 0, '1': 0, '2': 0 },
      { '0': 0, '1': 0, '2': 0 },
      { '0': 0, '1': 0, '2': 0 },
    ]
    const isCreate = nowKey == 'create'

    var needShowSaveDatas = false

    if (
      !isCreate &&
      modify_Datas &&
      selectedStrategy &&
      selectedStrategy.Datas
    ) {
      for (var ind = 0; ind < selectedStrategy.Datas.length; ind++) {
        // console.log(selectedStrategy.Datas[ind] + "||" + modify_Datas[ind])

        for (var ind2 in selectedStrategy.Datas[ind]) {
          if (selectedStrategy.Datas[ind][ind2] != modify_Datas[ind][ind2]) {
            needShowSaveDatas = true
            console.log(
              selectedStrategy.Datas[ind][ind2] + '--' + modify_Datas[ind][ind2]
            )
            break
          }
        }
      }
    }

    const cloumn = [
      //时间段   起始亮度   和放电速率
      {
        title: <Trans>Time Slot</Trans>, //电池电压
        dataIndex: 'a',
        key: 'V',
        render: (text, record, index) => {
          return (
            <InputNumber
              step={10}
              size="small"
              value={text ? text : '0'}
              onChange={e => {
                var targetDatas = isCreate ? create_Datas : modify_Datas
                if (!targetDatas) {
                  targetDatas = []
                  while (targetDatas.length < 5) {
                    targetDatas.push({})
                  }
                }
                targetDatas[index]['a'] = e
                this.setState(
                  isCreate
                    ? { create_Datas: targetDatas }
                    : { modify_Datas: targetDatas }
                )
              }}
            />
          )
        },
      },
      {
        title: <Trans>Initial Brightness</Trans>, //电流
        dataIndex: 'b',
        key: 'E',
        render: (text, record, index) => {
          return (
            <InputNumber
              size="small"
              value={text ? text : '0'}
              onChange={e => {
                var targetDatas = isCreate ? create_Datas : modify_Datas
                if (!targetDatas) {
                  targetDatas = []
                  while (targetDatas.length < 5) {
                    targetDatas.push({})
                  }
                }
                targetDatas[index]['b'] = e
                this.setState(
                  isCreate
                    ? { create_Datas: targetDatas }
                    : { modify_Datas: targetDatas }
                )
              }}
            />
          )
        },
      },
      {
        title: <Trans>Discharge Rate</Trans>, //电流
        dataIndex: 'c',
        key: 'E',
        render: (text, record, index) => {
          return (
            <InputNumber
              size="small"
              value={text ? text : '0'}
              onChange={e => {
                var targetDatas = isCreate ? create_Datas : modify_Datas
                if (!targetDatas) {
                  targetDatas = []
                  while (targetDatas.length < 5) {
                    targetDatas.push({})
                  }
                }
                targetDatas[index]['c'] = e
                this.setState(
                  isCreate
                    ? { create_Datas: targetDatas }
                    : { modify_Datas: targetDatas }
                )
              }}
            />
          )
        },
      },
    ]
    const selectNote =
      selectedStrategy && selectedStrategy.Note ? selectedStrategy.Note : ''
    const showModifyNoteSave = modify_Note !== selectNote
    const queryLoad = loading.effects[`multicmd/queryStrategy`]
    const TableSource =
      nowKey == 'create'
        ? create_Datas
          ? create_Datas
          : defaultValue
        : modify_Datas
        ? modify_Datas
        : selectedStrategy
        ? selectedStrategy.Datas
        : defaultValue
    const createStrategyloading = loading.effects[`multicmd/createStrategy`]
    const onCancel = () => {
      dispatch({
        type: 'multicmd/updateState',
        payload: { EditStrategyShow: false },
      })
    }
    const queryStrategy = () => {
      dispatch({
        type: 'multicmd/queryStrategy',
      })
    }
    const deleteStrategy = () => {
      dispatch({
        type: 'multicmd/deleteStrategy',
        payload: { objectId: modify_objectId },
      }).then(() => {
        this.setState({
          selectedStrategy: undefined,
          modify_objectId: undefined,
          modify_Name: '',
          modify_Note: '',
          modify_Datas: undefined,
        })
        queryStrategy()
      })
    }
    const updateStrategy = () => {
      // updateStrategy
      const newStra = {
        objectId: modify_objectId,
        Name: modify_Name,
        Note: modify_Note,
        Datas: modify_Datas,
      }
      dispatch({
        type: 'multicmd/updateStrategy',
        payload: newStra,
      }).then(error => {
        const { objectId, Name, Note, Datas } = newStra
        this.setState({
          selectedStrategy: newStra,
          modify_objectId: objectId,
          modify_Name: Name,
          modify_Note: Note,
          modify_Datas: JSON.parse(JSON.stringify(Datas)),
        })
      })
    }
    const createStrategy = () => {
      if (!create_Name) {
        message.error('请输入策略名称')
        return
      }
      dispatch({
        type: 'multicmd/createStrategy',
        payload: {
          Name: create_Name,
          Note: create_Note,
          Datas: create_Datas,
        },
      })
    }
    return (
      <Modal
        visible={EditStrategyShow}
        title={i18n.t`Lighting Strategy`}
        onCancel={onCancel}
        footer={[
          <Button key="Cancel" onClick={onCancel}>
            <Trans>Cancel</Trans>
          </Button>,
          nowKey == 'create' && (
            <Button
              key="create"
              onClick={e => {
                createStrategy()
              }}
              loading={createStrategyloading}
            >
              <Trans>Upload strategy</Trans>
            </Button>
          ),
          <Button
            key="create2"
            type="primary"
            onClick={e => {
              // choosedCmds
              const newchoosedCmds = choosedCmds
              newchoosedCmds[LightStrategyKey] = isCreate
                ? {
                    Name: create_Name,
                    Note: create_Note,
                    Datas: create_Datas,
                  }
                : {
                    Name: modify_Name,
                    Note: modify_Note,
                    Datas: modify_Datas,
                    objectId: modify_objectId,
                  }
              dispatch({
                type: 'multicmd/updateState',
                payload: {
                  choosedCmds: {
                    ...newchoosedCmds,
                  },
                },
              })
              onCancel()
            }}
          >
            <Trans>填入策略</Trans>
          </Button>,
        ]}
      >
        <Tabs
          activeKey={nowKey}
          tabBarStyle={{ marginTop: -10 }}
          style={{ marginTop: -15 }}
          onChange={key => {
            queryStrategy()
            dispatch({ type: 'multicmd/updateState', payload: { nowKey: key } })
          }}
        >
          <TabPane tab={i18n.t`New Strategy`} key="create">
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                marginBottom: 10,
              }}
            >
              <div style={{ width: 50 }}>
                <Trans>Name</Trans>：
              </div>
              <Input
                style={{ width: 200 }}
                size="small"
                value={create_Name}
                onChange={e => {
                  this.setState({ create_Name: e.target.value })
                }}
              />
            </div>
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                marginBottom: 10,
              }}
            >
              <div style={{ width: 50 }}>
                <Trans>Note</Trans>：
              </div>
              <Input
                style={{ width: 200 }}
                size="small"
                value={create_Note}
                onChange={e => {
                  this.setState({ create_Note: e.target.value })
                }}
              />
            </div>
          </TabPane>
          <TabPane tab={i18n.t`Select Strategy`} key="select">
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                marginBottom: 10,
              }}
            >
              <div style={{ width: 50 }}>
                <Trans>Name</Trans>：
              </div>
              <Select
                style={{ width: 200, marginRight: 10 }}
                size="small"
                value={modify_objectId}
                onSelect={val => {
                  var target = {}
                  for (var ind = 0; ind < AllStrategy.length; ind++) {
                    const { objectId } = AllStrategy[ind]
                      ? AllStrategy[ind]
                      : {}
                    if (objectId == val) {
                      target = AllStrategy[ind]
                    }
                  }
                  const { objectId, Name, Note, Datas } = target
                  // dispatch({ type: '' })
                  this.setState({
                    selectedStrategy: target,
                    modify_objectId: val,
                    modify_Name: Name,
                    modify_Note: Note,
                    modify_Datas: JSON.parse(JSON.stringify(Datas)),
                  })
                }}
                loading={queryLoad}
              >
                {AllStrategy.map((item, ind) => {
                  const { objectId, Name, Note } = item
                  return (
                    <Select.Option value={objectId} key={objectId}>
                      <div style={{}}>{Name}</div>
                    </Select.Option>
                  )
                })}
              </Select>
              <Button
                size="small"
                type="danger"
                disabled={!modify_objectId}
                onClick={e => {
                  deleteStrategy()
                }}
              >
                <Icon type="delete" />
                <Trans>Delete</Trans>
              </Button>
            </div>
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                marginBottom: 10,
              }}
            >
              <div style={{ width: 50 }}>
                <Trans>Note</Trans>：
              </div>
              <Input
                style={{ width: 200, marginRight: 10 }}
                size="small"
                value={modify_Note}
                onChange={e => {
                  this.setState({ modify_Note: e.target.value })
                }}
              />
              {showModifyNoteSave && (
                <span>
                  <Button
                    type="primary"
                    style={{ marginRight: 5 }}
                    size="small"
                  >
                    <Trans>Save</Trans>
                  </Button>
                  <Button
                    type="dashed"
                    size="small"
                    onClick={e => {
                      this.setState({
                        modify_Note: selectedStrategy.Note
                          ? selectedStrategy.Note
                          : '',
                      })
                    }}
                  >
                    <Trans>Cancel</Trans>
                  </Button>
                </span>
              )}
            </div>
          </TabPane>
        </Tabs>

        <div
          style={{ display: 'flex', alignItems: 'center', marginBottom: 10 }}
        >
          <div style={{ width: 50 }}>
            <Trans>Strategy</Trans>：
          </div>
          {needShowSaveDatas && (
            <span>
              <Button
                type="primary"
                style={{ marginRight: 10 }}
                size="small"
                onClick={e => {
                  updateStrategy()
                }}
              >
                <Trans>Save</Trans>
              </Button>
              <Button
                type="dashed"
                size="small"
                onClick={e => {
                  const { Datas } = selectedStrategy
                  this.setState({
                    modify_Datas: JSON.parse(JSON.stringify(Datas)),
                  })
                }}
              >
                <Trans>Cancel</Trans>
              </Button>
            </span>
          )}
        </div>

        <Table
          columns={cloumn}
          size="small"
          style={{ padding: 0, margin: 0 }}
          bordered={true}
          dataSource={TableSource}
          pagination={false}
          onHeaderRow={(column, index) => {
            return { style: { background: 'transparent' } }
          }}
          style={{
            marginTop: 10,
          }}
        />
      </Modal>
    )
  }
}

@withI18n()
@connect(({ multicmd, app, loading }) => {
  const { isMobile } = app
  return { multicmd, isMobile, loading }
})
class CommandList extends React.Component {
  render() {
    const { location, i18n, multicmd, isMobile, loading, dispatch } = this.props
    const { choosedCmds, EditStrategyShow, checkedCmdKeys } = multicmd
    const cmds = [LightStrategyKey, LightKey]
    const queryStrategy = () => {
      dispatch({
        type: 'multicmd/queryStrategy',
      })
    }
    const OpenStrategyEdit = () => {
      queryStrategy()
      dispatch({
        type: 'multicmd/updateState',
        payload: { EditStrategyShow: true },
      })
    }
    const renderCard = item => {
      const target = choosedCmds[item]

      const cardBaseStyle = {
        borderColor: 'rgb(200,200,200)', //'rgb(24,144,255)',
        borderRadius: 10,
        marginRight: 10,
        width: 180,
        height: 210,
        padding: 0,
      }
      const bodystyle = {
        padding: 10,
        paddingLeft: 15,
        paddingRight: 15,
      }
      const makeOnCardClick = (key, checked) => {
        var target = key
        if (checkedCmdKeys == key) {
          target = undefined
        }
        return e => {
          // if()
          // if (checkedCmdKeys.indexOf(key) != -1) {
          //   checkedCmdKeys.remove(key)
          // } else {
          //   checkedCmdKeys.push(key)
          // }
          dispatch({
            type: 'multicmd/updateState',
            payload: {
              checkedCmdKeys: target, //JSON.parse(JSON.stringify(checkedCmdKeys)),
            },
          })
        }
      }
      const checked = checkedCmdKeys == item //checkedCmdKeys.indexOf(item) != -1

      if (item == LightStrategyKey) {
        const { Datas, Name, Note } = target ? target : {}
        const cellprops = {
          onHeaderCell: column => {
            return {
              style: {
                background: 'transparent',
                paddingTop: 0,
                paddingBottom: 0,
                marginTop: 0,
                marginBottom: 0,
              },
            }
          },
          onCell: column => {
            return {
              onClick: () => {},
              style: {
                background: 'transparent',
                paddingTop: 0,
                paddingBottom: 0,
                marginTop: 0,
                marginBottom: 0,
              },
            }
          },
        }
        const cloumn = [
          {
            title: <Trans>Time Slot</Trans>, //电池电压
            dataIndex: 'a',
            key: 'V',
            render: (text, record, index) => {
              return text ? text : '0'
            },
            ...cellprops,
          },
          {
            title: <Trans>Initial Brightness</Trans>, //电流
            dataIndex: 'b',
            key: 'E',
            render: (text, record, index) => {
              return text ? text : '0'
            },
            ...cellprops,
          },
          {
            title: <Trans>Discharge Rate</Trans>, //电流
            dataIndex: 'c',
            key: 'E2',
            render: (text, record, index) => {
              return text ? text : '0'
            },
            ...cellprops,
          },
        ]
        // target
        return (
          <Card
            hoverable
            style={{
              ...cardBaseStyle,
              width: 250,
              cursor: target ? 'pointer' : 'default',
              borderColor: checked ? 'rgb(24,144,255)' : 'rgb(200,200,200)',
              borderWidth: checked ? 2 : 1,
            }}
            bodyStyle={{ ...bodystyle }}
          >
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
              }}
            >
              <div
                style={{
                  fontWeight: 'bold',
                  fontSize: 15,
                  alignItems: 'center',
                }}
              >
                <Switch
                  size="small"
                  disabled={!choosedCmds[item]}
                  checked={checked}
                  onClick={makeOnCardClick(item)}
                  style={{ marginRight: 5 }}
                />
                <Trans>Lighting Strategy</Trans>
              </div>
              <div style={{}}>
                {target && (
                  <Fragment>
                    <Tooltip title={i18n.t`Edit Strategy`}>
                      <Button
                        style={{ display: 'inline' }}
                        size="small"
                        onClick={e => {
                          OpenStrategyEdit()
                        }}
                      >
                        <Icon type="edit" />
                      </Button>
                    </Tooltip>
                  </Fragment>
                )}
              </div>
            </div>
            <div
              style={{
                height: 160,
                marginTop: 5,
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
              }}
            >
              {target ? (
                <Table
                  columns={cloumn}
                  size="small"
                  style={{
                    padding: 0,
                    margin: 0,
                    border: 'solid',
                    borderColor: 'rgb(200,200,200)',
                    borderWidth: 2,
                    borderRadius: 5,
                    //checked ?: "rgb(24,144,255)"
                  }}
                  bordered={true}
                  dataSource={Datas}
                  pagination={false}
                  onHeaderRow={column => {
                    return {
                      style: {
                        background: 'transparent',
                        padding: 0,
                        height: 5,
                      },
                    }
                  }}
                  onRow={column => {
                    return {
                      onClick: () => {},
                      style: {
                        background: 'transparent',
                        padding: 0,
                        margin: 0,
                        height: 5,
                      },
                    }
                  }}
                />
              ) : (
                <div
                  style={{
                    textAlign: 'center',
                    fontWeight: 'bold',
                  }}
                >
                  <Button
                    type="primary"
                    onClick={e => {
                      dispatch({
                        type: 'multicmd/updateState',
                        payload: { nowKey: 'select' },
                      })
                      OpenStrategyEdit()
                    }}
                  >
                    <Trans>Select Strategy</Trans>
                  </Button>
                  <br />
                  <Trans>Or</Trans>
                  <br />
                  <Button
                    onClick={e => {
                      dispatch({
                        type: 'multicmd/updateState',
                        payload: { nowKey: 'create' },
                      })
                      OpenStrategyEdit()
                    }}
                  >
                    <Trans>Create Strategy</Trans>
                  </Button>
                </div>
              )}
            </div>
          </Card>
        )
      } else if (item == LightKey) {
        const target = choosedCmds[item]
        const tmpLightDegree = (target ? target : {}).LightDegree
        const tmpLightDuration = (target ? target : {}).LightDuration
        const canswitch =
          tmpLightDegree != undefined && tmpLightDuration != undefined
        return (
          <Card
            hoverable
            style={{
              ...cardBaseStyle,
              borderColor: checked ? 'rgb(24,144,255)' : 'rgb(200,200,200)',
              borderWidth: checked ? 2 : 1,
            }}
            bodyStyle={{ ...bodystyle }}
            // onClick={makeOnCardClick(item)}
          >
            <div
              style={{ fontWeight: 'bold', fontSize: 15, alignItems: 'center' }}
            >
              <Switch
                size="small"
                disabled={!canswitch}
                checked={checked}
                onClick={makeOnCardClick(item)}
                style={{ marginRight: 5 }}
              />
              <Trans>Set Brightness</Trans>
            </div>
            <div style={{}}>
              <div style={{ minWidth: 60 }}>
                <Trans>Brightness</Trans>:
              </div>
              <InputNumber
                size="small"
                value={tmpLightDegree}
                min={0}
                max={100}
                onChange={value => {
                  const newchoosedCmds = JSON.parse(JSON.stringify(choosedCmds))
                  newchoosedCmds[item] = {
                    ...newchoosedCmds[item],
                    Name: i18n.t`Set Brightness`,
                    LightDegree: value,
                  }
                  dispatch({
                    type: 'multicmd/updateState',
                    payload: {
                      choosedCmds: newchoosedCmds,
                    },
                  })
                }}
                style={{ width: '100%' }}
              />
            </div>
            <div style={{ marginTop: 5 }}>
              <div style={{ minWidth: 60 }}>
                <Trans>Lighting time</Trans>:
              </div>
              <InputNumber
                size="small"
                value={tmpLightDuration}
                min={0}
                max={65535}
                onChange={value => {
                  const newchoosedCmds = JSON.parse(JSON.stringify(choosedCmds))
                  newchoosedCmds[item] = {
                    ...newchoosedCmds[item],
                    Name: i18n.t`Set Brightness`,
                    LightDuration: value,
                  }
                  dispatch({
                    type: 'multicmd/updateState',
                    payload: {
                      choosedCmds: newchoosedCmds,
                    },
                  })
                }}
                style={{ width: '100%' }}
              />
            </div>
          </Card>
        )
      } else {
        return null
      }
    }
    return (
      <Fragment>
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          <Title level={4} style={{ minWidth: 100 }}>
            <Trans>Command List</Trans>:
          </Title>
          <Alert
            message={
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                }}
              >
                <div style={{ marginRight: 5 }}>
                  <div
                    style={{
                      display: 'inline',
                      fontWeight: 'bold',
                      marginRight: 10,
                    }}
                  >
                    {i18n.t`Selected command`}:
                  </div>
                  <div style={{ display: 'inline' }}>
                    {checkedCmdKeys && choosedCmds[checkedCmdKeys] ? ( //&& checkedCmdKeys.length > 0
                      <Tag>
                        {choosedCmds[checkedCmdKeys].Name
                          ? choosedCmds[checkedCmdKeys].Name
                          : i18n.t`Temporary strategy`}
                      </Tag>
                    ) : (
                      <Tag>
                        <Trans>None</Trans>
                      </Tag>
                    )}
                  </div>
                </div>
                <div style={{ display: 'inline' }}>
                  <Tooltip title={i18n.t`Clear Selection`}>
                    <Button
                      size="small"
                      onClick={e => {
                        dispatch({
                          type: 'multicmd/updateState',
                          payload: { checkedCmdKeys: undefined },
                        })
                      }}
                    >
                      <Icon type="delete" />
                    </Button>
                  </Tooltip>
                </div>
              </div>
            }
            style={{
              marginBottom: 5,
              background: '#fff',
            }}
          />
        </div>
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            overflowX: 'scroll',
            overflowY: 'hidden',
            height: cmdlistHeight,
          }}
        >
          {renderCard(LightStrategyKey)}
          {renderCard(LightKey)}
        </div>
      </Fragment>
    )
  }
}

@withI18n()
@connect(({ multicmd, app, loading }) => {
  const { isMobile } = app
  return { multicmd, isMobile, loading }
})
class ExtrasProps extends React.Component {
  render() {
    const { multicmd, dispatch } = this.props
    const { Note, Repeat } = multicmd
    return (
      <div style={{ minHeight: extraspropsheight }}>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <Title level={4} style={{ minWidth: 100 }}>
            <Trans>Execution Parameter</Trans>:
          </Title>
        </div>
        <div>
          <div>
            <Trans>Number of repetitions after failure</Trans>:
          </div>
          <InputNumber
            min={0}
            max={10}
            value={Repeat}
            style={{ width: '100%' }}
            onChange={e => {
              dispatch({ type: 'multicmd/updateState', payload: { Repeat: e } })
            }}
          />
          <div>
            <Trans>Note</Trans>:
          </div>
          <Input
            value={Note}
            onChange={e => {
              dispatch({
                type: 'multicmd/updateState',
                payload: { Note: e.target.value },
              })
            }}
          />
        </div>
      </div>
    )
  }
}

@withI18n()
@connect(({ multicmd, app, loading }) => {
  const { isMobile } = app
  return { multicmd, isMobile, loading }
})
class MultiCmd extends React.Component {
  componentWillUnmount() {
    const { dispatch } = this.props
    dispatch({ type: 'multicmd/clearstore' })
  }

  componentDidMount() {
    this.props.dispatch({ type: 'multicmd/queryProjects' })
  }

  render() {
    const { location, i18n, multicmd, isMobile, loading, dispatch } = this.props
    const { checkedKeys, choosedCmds, checkedCmdKeys } = multicmd
    // const cmds = [LightStrategyKey, LightKey]
    // const queryStrategy = () => {
    //   dispatch({
    //     type: 'multicmd/queryStrategy',
    //   })
    // }
    const canInvoke =
      checkedCmdKeys &&
      checkedKeys &&
      checkedKeys.length > 0 &&
      choosedCmds &&
      JSON.stringify(choosedCmds) != '{}'
    return (
      <Page inner>
        <Content>
          <Layout
            style={{
              background: 'transparent',
              marginBottom: 0,
              paddingBottom: 0,
            }}
          >
            <ProjectDeviceList />
            <div
              style={{
                width: 2,
                height: topHieght + 40 - 20,
                marginTop: 10,
                marginBottom: 10,
                marginRight: 10,
                background: 'rgb(244,244,244)',
              }}
            />
            <Content>
              <CommandList />
              <ExtrasProps />
            </Content>
          </Layout>

          <span
            style={{ marginTop: 5, display: 'flex', justifyContent: 'center' }}
          >
            {/* float: "center", */}
            <Button
              type="primary"
              style={{ width: 150 }}
              onClick={e => {
                dispatch({ type: 'multicmd/InvokeMission' })
              }}
              loading={loading.effects['multicmd/InvokeMission']}
              disabled={!canInvoke}
            >
              <Trans>Execute</Trans>
            </Button>
          </span>
        </Content>

        <EditStrategy />
      </Page>
    )
  }
}

export default MultiCmd
